/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.ruggear.rtc;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;

import com.receiver.OnePixelReceiver;
import com.service.AliveJobService;
import com.service.RtcService;

import org.apache.cordova.*;

import java.util.List;

public class MainActivity extends CordovaActivity
{
    public final static String myTag = "myVideo";
    private OnePixelReceiver onePixelReceiver = null;
    private static int MyRequestCode_isIgnoringBatter = 4001;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Log.w(myTag,"MainActivity onCreate");
        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
            moveTaskToBack(true);
        }

        // Set by <content src="index.html" /> in config.xml
        Log.w(myTag,"loadUrl before");
        loadUrl(launchUrl);
        Log.w(myTag,"loadUrl after");

        // 保活1 1像素保活方案 注册监听屏幕的广播 第二个link：https://www.jianshu.com/p/20e3dfc7f23c
        // registerPixelReceiver(); 由于老是亮屏返回界面 暂时关闭 想到可以receiver放到service中试试

        // 保活3 前台服务方案
        startBeforeService();
        // 保活2 电池优化方案
        startIgnoringBatter();

        // 保活4 jobScheduler方案
        jobScheduler();

    }

    @Override
    protected void onResume() {
        Log.w(myTag,"MainActivity onResume");
        super.onResume();
    }

    @Override
    protected void onPause() {
        Log.w(myTag,"MainActivity onPause");
        super.onPause();
    }

    @Override
    public void onDestroy() {
        Log.w(myTag,"MainActivity onDestroy");
        if(onePixelReceiver!=null){
            unregisterReceiver(onePixelReceiver);
            onePixelReceiver = null;
        }
        super.onDestroy();
    }

    /** 链接：掘金 https://juejin.im/post/5dfaeccbf265da33910a441d @RequiresApi(api = Build.VERSION_CODES.M)*/
    @TargetApi(Build.VERSION_CODES.M)
    private boolean isIgnoringBatteryOptimizations() {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
        }
        return isIgnoring;
    }

    // @RequiresApi(api = Build.VERSION_CODES.M)
    public void requestIgnoreBatteryOptimizations() {
        try {
            // 以下是部分手机的厂商判断，跳转方法及对应设置步骤，跳转方法不保证在所有版本上都能成功跳转，都需要加 try catch.
            // https://www.jianshu.com/p/8736f4fadb66
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent,MyRequestCode_isIgnoringBatter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 权限申请/系统设置申请后的返回结果检查
     * @param requestCode The request code originally supplied to startActivityForResult(),
     *                    allowing you to identify who this result came from.
     * @param resultCode  The integer result code returned by the child activity through its setResult().
     * @param intent      An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == MyRequestCode_isIgnoringBatter) {
            if(resultCode == RESULT_OK){
                Log.w(myTag,"权限/申请成功,申请代号："+requestCode);
            }else{
                Log.w(myTag,"权限/申请被拒绝,申请代号："+requestCode);
            }
        }
    }

    // 保活1 1像素保活方案 注册监听屏幕的广播
    private void registerPixelReceiver(){
        if(onePixelReceiver == null){
            onePixelReceiver = new OnePixelReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.SCREEN_OFF");
        intentFilter.addAction("android.intent.action.SCREEN_ON");
        intentFilter.addAction("android.intent.action.USER_PRESENT");
        registerReceiver(onePixelReceiver, intentFilter);
    }

    /** 保活3 前台服务方案 */
    private void startBeforeService(){
        if (isServiceRunning("com.service.RtcService")){
            Log.w(myTag,"服务正在运行 return");
            return;
        }

        Intent rtcService = new Intent(this, RtcService.class);
        rtcService.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// FLAG_ACTIVITY_REORDER_TO_FRONT 如果有就复用 待检测 FLAG_ACTIVITY_NEW_TASK
        this.startService(rtcService);
    }

    /** 保活2 电池优化方案 */
    private void startIgnoringBatter(){
        boolean isIgnoringBatter;// 是否电池续航时间优化
        isIgnoringBatter = isIgnoringBatteryOptimizations();
        if(!isIgnoringBatter){
            Log.w(myTag,"是否电池续航时间优化：" + isIgnoringBatteryOptimizations());
            Log.w(myTag,"不在电池续航时间优化：" );
            requestIgnoreBatteryOptimizations();
        }else{
            Log.w(myTag,"是否电池续航时间优化：" + isIgnoringBatteryOptimizations());
            Log.w(myTag,"在电池续航时间优化：" );
        }
    }

    /**
     * 判断服务是否运行
     */
    private boolean isServiceRunning(final String className) {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> info = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (info == null || info.size() == 0) return false;
        for (ActivityManager.RunningServiceInfo aInfo : info) {
            if (className.equals(aInfo.service.getClassName())) return true;
        }
        return false;
    }

    /** 保活4 jobScheduler方案 */
    private void jobScheduler(){
        if (isServiceRunning("com.service.AliveJobService")){
            Log.w(myTag,"AliveJobService 服务正在运行 return");
            return;
        }
        Intent aliveJobService = new Intent(this, AliveJobService.class);
        aliveJobService.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// FLAG_ACTIVITY_REORDER_TO_FRONT 如果有就复用 待检测 FLAG_ACTIVITY_NEW_TASK
        this.startService(aliveJobService);
    }

}
